<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>论坛中文网</title>
</head>

<body>
	<div style="padding: 10px; margin: 0px auto; max-width: 1600px;">

		<button type="submit" class="btn btn-default" onclick="javascript: window.open('/', '_self')">
			<span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span> 回到首页
		</button>
		<h1>发布文章</h1>

		<form role="form">
			<div class="form-group">
				<label for="title">标题</label>
				<input type="text" class="form-control" id="title" placeholder="请输入文章标题">
			</div>
			<div class="form-group">
				<img style="width: 200px; height: 150px;" id="avatar">
			</div>
			<div class="form-group">
				<label for="inputfile">文章图片</label>
				<input type="file" id="inputfile" name="file">
				<input type="hidden" id="articleId" name="articleId"/>
				<p class="help-block">请选择文章图片</p>
			</div>
			<div class="form-group">
				<label for="content">正文</label>
				<textarea class="form-control" rows="10" id="content"></textarea>
			</div>
			<button type="button" class="btn btn-primary" onclick="articlePublish()">立即发布</button>
		</form>
	</div>

</body>

<!-- 引入jquery -->
<script src="/js/jquery/jquery-1.10.2.min.js"></script>
<!-- 引入bootstrap -->
<link href="/js/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<script src="/js/bootstrap/js/bootstrap.min.js"></script>
<!-- 引入main.js -->
<script src="/js/main.js"></script>

<script>

/**
 * 进入页面就会执行
 */
 $(function() {
	// 获取当前登录用户，会currentUser赋值
	getCurrentUser().then(() => {
		if(currentUser==null) {
			alert("登录已过期")
      		window.location.replace("/html/login.html");
		}
	});
});

/**
 * 发布文章
 * 先传文章数据（json）回调传图片（附加文章id）
 */
function articlePublish() {
	const article = {
		"title": $("#title").val(),
		"content": $("#content").val()
	};
	if(confirm("是否确认发布文章？")) {
		$.ajax({
			url: BACK_URL + "/article",
			method: "post",
			contentType:"application/json;charset=utf-8",
			data: JSON.stringify(article),
			success: function (result) {
				if(result.code==200) {
					// 传图片，附加id，用js触发表单的提交
					// $("#articleId").val(result.data.id);
					// $("#fomrId").submit();

					alert("发布成功");
					window.location.replace("/");// 跳转到主页
				}
			}
		});

		// $.ajax({
		// 	url: BACK_URL + "/article/list",
		// 	method: "get",
		// 	success: function (result) {
		// 		console.log(result);
		// 	}
		// });
	}
}

</script>

</html>